#
# peerscape.discovery.discover
#
# Copyright 2007-2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Toni Ruottu <toni.ruottu@iki.fi>
#          Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import logging
from random import shuffle
from threading import Thread, currentThread

from messkit.nson import decode
from peerscape.discovery import lookup
from peerscape.discovery.advertise import VERSION

discovery_threads = []

def discover(key, maxvals=10, cb=None):
    key = key + '-' + VERSION
    if cb is not None:
        _discover_async(key, maxvals, cb)
    else:
        return _discover_sync(key, maxvals)

def _discover_async(key, maxvals, cb):
    thread = Thread(target = _run,
                    args = (_discover_sync, cb, key, maxvals),
                    name = 'openlookup-discovery-thread')
    thread.setDaemon(True)
    thread.start()

def _discover_sync(key, maxvals):
    # Fetching all values and sampling won't scale, so we have to
    # request just a reasonable number.  OpenDHT would return the same
    # values each time, but OpenLookup at least starts with a randomly
    # selected value.
    try:
        values = lookup.get(key, maxvals)
    except lookup.Error, e:
        logging.debug('Discovery: %s' % e)
        return None

    shuffle(values)
    return list(_decode_all(values))

def _decode_all(values):
    for v in values:
        try:
            yield decode(v) # Beware that tuples come out as lists!
        except ValueError:
            logging.warning('Discovery: Found garbage in OpenLookup.')

def _run(f, cb, *args):
    thread = currentThread()
    discovery_threads.append(thread)
    try:
        result = f(*args)
        if result is not None:
            cb(result)
    finally:
        discovery_threads.remove(thread)
